package org.taobao.ibatiside.ui.action;

import org.eclipse.datatools.connectivity.IConnectionProfile;
import org.eclipse.datatools.connectivity.sqm.core.rte.ICatalogObject;
import org.eclipse.datatools.modelbase.sql.tables.Column;
import org.eclipse.datatools.modelbase.sql.tables.Table;
import org.eclipse.datatools.sqltools.sql.util.ModelUtil;
import org.eclipse.emf.common.util.EList;
import org.taobao.ibatiside.ui.Activator;

public class DseNewUpdateAction extends DseViewerAction {
	public static final String ID="org.taobao.ibatiside.ui.action.dse.update";
	public DseNewUpdateAction() {
		super();
		setId(ID);
		setText("New Update");
		setImageDescriptor(Activator.getIcon("op16/update.png"));
		setDescription("Create a new Update node in existed iBATIS configuration file");
	}
	@Override
	protected String sampleSQL() {
		Table table = getSelectedElement();
		IConnectionProfile icp = ModelUtil.getConnectionProfile(((ICatalogObject)table).getCatalogDatabase());
		StringBuffer sb = new StringBuffer("update ");
		if (table.getSchema() != null){
			sb.append(table.getSchema().getName()).append('.');
		}
		sb.append(table.getName());
		sb.append(" set ");
		EList columns = table.getColumns();
		for (int i = 0; i < columns.size(); i++){
			Column column = (Column) columns.get(i);
			if (!column.isPartOfPrimaryKey() && !column.isPartOfForeignKey()){
				sb.append(nameHelper.getNameInSQLFormat(column)).append('=').append(dtpFacade.getSampleValue(icp, column.getDataType()));
				break;
			}
		}
		for (int i = 0; i < columns.size(); i++){
			Column column = (Column) columns.get(i);
			if (column.isPartOfPrimaryKey()){
				if (i > 0)
					sb.append(" and ");
				else
					sb.append(" where ");
				sb.append(nameHelper.getNameInSQLFormat(column)).append("=");
				sb.append(dtpFacade.getSampleValue(icp,column.getDataType()));
			}
		}
		return sb.toString();
	}
}
